//
//  SelectPhotoPictureViewController.m
//  Rail
//
//  Created by hychen on 2018/3/4.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "SelectPhotoPictureViewController.h"
#import "DPPictureSelectorToolBar.h"
#import "SelectPhotoPictureGroupViewController.h"
#import "DPPictureSelectorCollectionView.h"
#import "DPPictureSelectorHeaderView.h"
#import "BMCustomButton.h"
#import "DPPictureSelectorCell.h"

@interface SelectPhotoPictureViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
// 默认相册模型
@property (nonatomic, strong) BMPhotoIOAlbumModel *firstAlbumModel;
/***  选中图片数组*/
@property (nonatomic, strong) NSMutableArray *selectedImageArray;
/***  工具*/
//@property (nonatomic, strong) DPPictureSelectorTool *picSelectorTool;
// 相册数组
@property (nonatomic, strong) NSArray<BMPhotoIOAlbumModel *> *albumArray;
// 照片数组
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UICollectionView *collectionView;
/***  导航栏标题*/
@property (nonatomic, strong) UIButton *navTitleButton;
/***  工具栏*/
@property (nonatomic, strong) DPPictureSelectorToolBar *toolBar;
/***  相片组控制器*/
@property (nonatomic, strong) SelectPhotoPictureGroupViewController *dpGroupVc;
@end

@implementation SelectPhotoPictureViewController


- (instancetype)init{
    if (self = [super init]) {
        NSArray *array = [BMPhotoIOTool sharedTool].albumArray;
        if (array && array.count > 0) {
            _firstAlbumModel = [BMPhotoIOTool sharedTool].albumArray.firstObject;
        }
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    [self setupChildController];
    
    BMWeakSelf
    [self setupPhotoDataWithPhotoIndex:0 completion:^{
        [weakSelf.collectionView reloadData];
    }];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    CGRect frame = self.view.bounds;
    frame.origin.y = 0;
    self.dpGroupVc.view.frame = frame;
}

// 初始化UI
- (void)setupUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    // 工具栏
    [self setupToolBar];
    // 布局
    [self setupCollectionView];
    // 导航栏
    [self setupNavItems];
}

// 布局
- (void)setupCollectionView
{
    DPPictureSelectorCollectionView *collectionView = [DPPictureSelectorCollectionView collectionView];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.bottom.equalTo(self.toolBar.mas_top);
    }];
    
    [self.collectionView reloadData];
    
    NSMutableArray *array = self.dataArray.lastObject;
    if ([array isKindOfClass:[NSArray class]]) {
        if (array.count<1) {
            return;
        }
    }else{
        return;
    }
    NSInteger item = ((NSMutableArray *)self.dataArray.lastObject).count - 1;
    NSIndexPath *path = [NSIndexPath indexPathForItem:item inSection:self.dataArray.count - 1];
    [self.collectionView scrollToItemAtIndexPath:path atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
}

// 导航栏
- (void)setupNavItems
{
    BMCustomButton *button = [[BMCustomButton alloc] init];
    button.customStyle = CustomButtonStyleImageRightTitleLeft;
    button.imageHeight = 5.5;
    button.imageWidth = 8;
    button.titleLabel.font = [UIFont systemFontOfSize:20 * SCREEN_WIDTH / 375.0];
    [button setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"DP_history_nav_title_down"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"DP_history_nav_title_up"] forState:UIControlStateSelected];
    [button setTitle:@"相机胶卷  " forState:UIControlStateNormal];
    [button addTarget:self action:@selector(titleButtonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = button;
    self.navTitleButton = button;
    [button sizeToFit];
}

- (void)setupToolBar
{
    __weak typeof (self) weakSelf = self;
    DPPictureSelectorToolBar *toolBar = [[DPPictureSelectorToolBar alloc] init];
    toolBar.backgroundColor = [UIColor whiteColor];
    toolBar.maxCount = self.maxSelectImageCount;
    toolBar.cancelButtonClickedBlock = ^(UIView *view, id object) {
        // 取消
        [weakSelf cancelSelectPictures];
    };
    
    toolBar.confirmButtonClickedBlock = ^(UIView *view, id object) {
        // 确定
        [weakSelf confirmSelectPictures];
    };
    [self.view addSubview:toolBar];
    self.toolBar = toolBar;
    [toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        
        make.bottom.mas_equalTo(IPHONEX_SCREEN?34:0);
        make.height.mas_equalTo(50);
    }];
}

// 图片数据
- (void)setupPhotoDataWithPhotoIndex:(NSInteger)index completion:(void(^)())completion{
    
    self.albumArray = [BMPhotoIOTool sharedTool].albumArray;
    BMPhotoIOAlbumModel *albumModel = [self.albumArray objectAtIndexSafe:index];
    [self reloadData:albumModel.name];
    if (IOS8) {
        id collection = albumModel.collection;
        if (collection) {
            [[BMPhotoIOTool sharedTool] photosWithCollection:collection finishBlcok:^(id obj1, id obj2) {
                BMWeakSelf
                NSMutableArray *array = nil;
                if ([obj1 isKindOfClass:[NSMutableArray class]]) {
                    array = (NSMutableArray *)obj1;
                }
                __block BOOL isFinished = [obj2 boolValue];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (array.count) {
                        if (isFinished) {
                            // 添加拍摄照片模型
                            //                            [array addObject:[BMPhotoIOPhotoModel cameraModel]];
                            [array insertObject:[BMPhotoIOPhotoModel cameraModel] atIndex:0];
                            if (completion) {
                                completion();
                            }
                        }
                        //                        [weakSelf.dataArray addObject:array];
                        [weakSelf.dataArray insertObject:array atIndex:0];
                    } else {
                        if (!weakSelf.dataArray.count) {
                            // 没有相片要添加默认相机
                            NSMutableArray *cameraArray = [NSMutableArray array];
                            [cameraArray addObject:[BMPhotoIOPhotoModel cameraModel]];
                            [weakSelf.dataArray addObject:cameraArray];
                            if (completion) {
                                completion();
                            }
                        }
                    }
                });
                
            }];
        }
    }else {
        id group = albumModel.group;
        [[BMPhotoIOTool sharedTool] photosWithAssetGroup:group finishBlcok:^(NSMutableArray *array, id object1) {
            BMWeakSelf
            __block BOOL isFinished = [object1 boolValue];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (array.count) {
                    if (isFinished) {
                        // 添加拍摄照片模型
                        //                        [array addObject:[BMPhotoIOPhotoModel cameraModel]];
                        [array insertObject:[BMPhotoIOPhotoModel cameraModel] atIndex:0];
                        if (completion) {
                            completion();
                        }
                    }
                    //                    [weakSelf.dataArray addObject:array];
                    [weakSelf.dataArray insertObject:array atIndex:0];
                } else {
                    if (!weakSelf.dataArray.count) {
                        // 没有相片要添加默认相机
                        NSMutableArray *cameraArray = [NSMutableArray array];
                        [cameraArray addObject:[BMPhotoIOPhotoModel cameraModel]];
                        [weakSelf.dataArray addObject:cameraArray];
                    }
                    if (completion) {
                        completion();
                    }
                }
                
            });
        }];
    }
}

// 相片组控制器
- (void)setupChildController
{
    // 相片组控制器
    __weak typeof (self) weakSelf = self;
    SelectPhotoPictureGroupViewController *dpGroupVc = [[SelectPhotoPictureGroupViewController alloc] init];
    dpGroupVc.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.view.height);
    dpGroupVc.selectPhotoGroup = ^(id object){
        //        [weakSelf.picSelectorTool.dataDict removeAllObjects];
        //        [weakSelf.picSelectorTool.dateArray removeAllObjects];
        //更新数据源
        [self updatePicturesDataSource:[object integerValue]];
        
        [weakSelf.collectionView reloadData];
        //        [weakSelf changePhotoGroupWithIndex:[object integerValue]];
        weakSelf.dpGroupVc.hidden = YES;
    };
    self.dpGroupVc = dpGroupVc;
    dpGroupVc.hidden = YES;
    [self addChildViewController:dpGroupVc];
    [self.view addSubview:dpGroupVc.view];
}

// 更新数据源
- (void)updatePicturesDataSource:(NSInteger)index{
    [self.dataArray removeAllObjects];
    BMWeakSelf
    [self setupPhotoDataWithPhotoIndex:index completion:^{
        [weakSelf.collectionView reloadData];
    }];
}
#pragma mark - 属性

- (NSMutableArray *)selectedImageArray
{
    if (!_selectedImageArray) {
        _selectedImageArray = [NSMutableArray array];
    }
    return _selectedImageArray;
}

//- (DPPictureSelectorTool *)picSelectorTool
//{
//    if (!_picSelectorTool) {
//        __weak typeof (self) weakSelf = self;
//        _picSelectorTool = [[DPPictureSelectorTool alloc] initWithDailyPhotoBlock:^(NSString *groupName){
////            NSTimer *timer = [NSTimer timerWithTimeInterval:0.1 target:weakSelf selector:@selector(reloadData:) userInfo:groupName repeats:NO];
////            [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
//            [weakSelf performSelector:@selector(reloadData:) withObject:groupName afterDelay:0.1];
////            [weakSelf reloadData:groupName];
//        }];
//    }
//    return _picSelectorTool;
//}

- (void)reloadData:(NSString *)groupName
{
    [self.collectionView reloadData];
    //    self.dpGroupVc.groupArray = self.picSelectorTool.photoGroupArray;
    self.dpGroupVc.groupArray = [BMPhotoIOTool sharedTool].albumArray;
    [self.navTitleButton setTitle:groupName forState:UIControlStateNormal];
    [self.navTitleButton sizeToFit];
}

- (void)setMaxSelectImageCount:(NSInteger)maxSelectImageCount
{
    _maxSelectImageCount = maxSelectImageCount;
    if (self.toolBar) {
        self.toolBar.maxCount = maxSelectImageCount;
    }
}

#pragma mark - collectionView代理
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    //    return self.picSelectorTool.dateArray.count;
    return self.dataArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    //    NSString *dateKey = [[self.picSelectorTool.dateArray objectAtIndex:section] formattedDateYYMMDD];
    //    NSArray *array = [self.picSelectorTool.dataDict objectForKey:dateKey];
    //    return array.count;
    NSArray *array = [self.dataArray objectAtIndexSafe:section];
    if (array && [array isKindOfClass:[NSArray class]]) {
        return array.count;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DPPictureSelectorCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([DPPictureSelectorCell class]) forIndexPath:indexPath];
    
    __weak typeof (self) weakSelf = self;
    cell.imageButtonDidClickedBlock = ^(UIView *view, id object) {
        [weakSelf selectImage:object button:(UIButton *)view];
    };
    //    NSString *dateKey = [[self.picSelectorTool.dateArray objectAtIndexSafe:indexPath.section] formattedDateYYMMDD];
    //    NSArray *array = [self.picSelectorTool.dataDict objectForKeySafe:dateKey];
    //    NSLog(@"index.section = %zd, index.row = %zd",indexPath.section, indexPath.row);
    //    ALAsset *asset = [array objectAtIndex:indexPath.row];
    
    NSArray *array = [self.dataArray objectAtIndexSafe:indexPath.section];
    if (array && [array isKindOfClass:[NSArray class]]) {
        BMPhotoIOPhotoModel *photo = [array objectAtIndexSafe:indexPath.row];
        cell.photo = photo;
    }
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableView =nil;
    if (kind ==UICollectionElementKindSectionHeader) {
        //定制头部视图的内容
        DPPictureSelectorHeaderView *headerV = (DPPictureSelectorHeaderView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"DPPictureSelectorHeaderView" forIndexPath:indexPath];
        //        NSDate *date = [self.picSelectorTool.dateArray objectAtIndex:indexPath.section];
        NSArray *array = [self.dataArray objectAtIndex:indexPath.section];
        if (array && [array isKindOfClass:[NSArray class]] && array.count>0) {
            BMPhotoIOPhotoModel *photo = [array firstObject];
            headerV.date = photo.createDateString;
            reusableView = headerV;
        }
        //        NSString *str = [date formattedDateYYMMDD];
        //        headerV.date = str;
        //        reusableView = headerV;
    }
    return reusableView;
}

#pragma mark - 事件方法
- (void)selectImage:(BMPhotoIOPhotoModel *)model button:(UIButton *)button
{
    if (!model) {
        return;
    }
    
    if (model.type == BMPhotoIOPhotoTypeCamera) {
        [self takePictureCamera];
        return;
    }
    
    // 附加属性
//    model.selected = YES;
    
    
    if (button.selected) {
        // 移除图片
        [self.selectedImageArray removeObject:model];
    } else {
        // 添加图片
        if (self.selectedImageArray.count >= self.maxSelectImageCount) {
//            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"最多只能选择9张图片" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"知道了", nil];
//            [alertView show];
            return;
        } else {
            [model getOriginalImage_BM];
            [model getThumbImage_BM];
            [self.selectedImageArray addObject:model];
        }
    }
    button.selected = !button.selected;
    model.selected = button.selected;
    self.toolBar.count = self.selectedImageArray.count;
}

- (void)titleButtonDidClicked:(UIButton *)button
{
    self.dpGroupVc.hidden = !self.dpGroupVc.hidden;
}

// 取消选择照片
- (void)cancelSelectPictures
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 确定选中相片
- (void)confirmSelectPictures
{
    if (!self.selectedImageArray.count) {
        // 没选
        [self cancelSelectPictures];
    } else {
        if (self.selectPhotoFinishBlock) {
            //            // 获取最新事件和所有时间是否同一天,--》 同步
            self.selectPhotoFinishBlock(self.selectedImageArray);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

// 更换相片组
//- (void)changePhotoGroupWithIndex:(NSInteger)index
//{
//    self.picSelectorTool.currentGroupIndex = index;
//}

// 调用相机
- (void)takePictureCamera
{
    if (self.selectedImageArray.count < self.maxSelectImageCount) {
        __weak typeof (self) weakSelf = self;
        [self dismissViewControllerAnimated:YES completion:^{
            if (weakSelf.takePictureCameraBlock) {
                weakSelf.takePictureCameraBlock();
            }
        }];
    } else {
        return;
    }
}

-(void)dealloc
{
    _collectionView.delegate = nil;
    _collectionView.dataSource = nil;
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    if ([self.childViewControllers containsObject:_dpGroupVc]) {
        [_dpGroupVc removeFromParentViewController];
    }
}

#pragma mark - 懒加载
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

@end
